package com.i5.distributedlock.core.key.strategy;

import com.i5.distributedlock.annotation.Key;
import com.i5.distributedlock.constant.LockCommonConstant;
import com.i5.distributedlock.core.key.LockKey.Builder;
import com.i5.distributedlock.core.key.RedisLockKey;
import com.i5.distributedlock.core.key.ZookeeperLockKey;
import com.i5.distributedlock.enumeration.LockScheme;
import com.i5.distributedlock.exception.KeyBuilderException;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @BelongsPackage: com.i5.distributedlock.core.strategy
 * @Author: mc0710
 * @CreateTime: 2019-04-17 10:00
 * @Description: 参数锁处理
 */
public class ParameterKeyStrategy extends KeyStrategy {

    public ParameterKeyStrategy(LockScheme scheme, String className, String methodName, Method realMethod,
                                Object[] args, String prefixName) {
        super(scheme, className, methodName, realMethod, args, prefixName);
    }

    @Override
    public Builder generateBuilder() throws KeyBuilderException {

        Builder keyBuilder;
        if (scheme == LockScheme.REDIS) {
            keyBuilder = RedisLockKey.newRedisKeyBuilder();
        } else {
            keyBuilder = ZookeeperLockKey.newZookeeperKeyBuilder();
        }

        for (int i = 0; i < realMethod.getParameters().length; i++) {
            if (realMethod.getParameters()[i].isAnnotationPresent(Key.class)) {
                if (StringUtils.isEmpty(prefixName)) {
                    keyBuilder.appendKey(wrapKeyTag(args[i].toString()));
                } else {
                    keyBuilder.appendKey(prefixName + LockCommonConstant.KEY_SPLIT_MARK + args[i].toString());
                }
            }
        }
        return keyBuilder;
    }

}
